﻿using UnityEngine;
using System.Collections;
using System.Collections.Generic;
using UnityEngine.UI;


public class Bar : MonoBehaviour {

    public Color color;
    public float value;
    public float Height;
    string title { get; set; }
    public float startTime;
    private float speed = 200;
    private float journeyLength;
    public string UnitsSymbol;
    public string Title
    {
        get { return title; }

        set
        {
            title = value;
            this.transform.GetChild(0).GetComponent<Text>().text = title;
        }
    }

    private Vector2 startMarker;
    private Vector2 endMarker;
    public float NormalizedScaler;
    public bool isDoneAnimating;
    public bool isAnimating;

   
    

    // Use this for initialization
    void Start()
    {        
        
        this.GetComponent<RectTransform>().sizeDelta = new Vector2(0, 0);
        NormalizedScaler = this.transform.parent.gameObject.GetComponent<RectTransform>().rect.size.x / this.transform.parent.gameObject.GetComponent<BarChart>().Max;
        this.GetComponent<RectTransform>().localScale = new Vector3(1, 1, 1);        
        journeyLength = Vector2.Distance(this.GetComponent<RectTransform>().sizeDelta, this.GetComponent<RectTransform>().sizeDelta + new Vector2(value * NormalizedScaler , Height));
        startMarker = this.GetComponent<RectTransform>().sizeDelta += new Vector2(0, Height);
        endMarker = this.GetComponent<RectTransform>().sizeDelta + new Vector2(value * NormalizedScaler, 0);
        this.transform.rotation = this.transform.parent.rotation;
    }

    // Update is called once per frame
    void Update()
    {
        if(isAnimating)
        {
            //while(this.GetComponent<RectTransform>().sizeDelta.y < value * NormalizedScaler)
            //{
            //    this.GetComponent<RectTransform>().sizeDelta = new Vector2(Width, this.GetComponent<RectTransform>().sizeDelta.y + .02f);
            //}
           
        

            float distCovered = (Time.time - startTime) * speed;
            float fracJourney = distCovered / journeyLength;
            this.GetComponent<RectTransform>().sizeDelta = Vector2.Lerp(startMarker, endMarker, fracJourney);
            this.transform.GetChild(1).GetComponent<Text>().text = ((int)(fracJourney * value)).ToString() + UnitsSymbol;

            if (this.GetComponent<RectTransform>().sizeDelta == endMarker)
            {
                isDoneAnimating = true;
                isAnimating = false;
            }

        }
    }


    
    public void Animate()
    {        
        isAnimating = true;
    }
       

}